<template>
  <div>
    <el-row :gutter="10">
      <el-col :span="8">
        <div class="grid-content">
          <div class="metric-label">迭代概览: {{ sprint.name }}</div>
          <div class="metrics-container">
            <div class="metric-item">
              <div class="metric-label">日期</div>
              <el-progress
                :width="100"
                type="circle"
                :percentage="50"
                color="#409EFF"
                class="progress-circle"
              ></el-progress>
            </div>
            <div class="metric-item">
              <div class="metric-label">故事点</div>
              <el-progress
                :width="100"
                type="circle"
                :percentage="40"
                color="#67C23A"
                class="progress-circle"
              ></el-progress>
            </div>
            <div class="metric-item">
              <div class="metric-label">工作项</div>
              <el-progress
                :width="100"
                type="circle"
                :percentage="90"
                color="#E6A23C"
                class="progress-circle"
              ></el-progress>
            </div>
          </div>
          <div class="status-info">
            <el-row :gutter="10">
              <el-col :span="12">
                <div class="status-item">
                  <div class="status-label">状态</div>
                  <dict-tag :options="dict.type.sprint_status" :value="sprint.status"/>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="status-item">
                  <div class="status-label">负责人</div>
                  <div class="status-value"><user-and-avatar :user-id="sprint.assigneeId"></user-and-avatar></div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="status-item">
                  <div class="status-label">开始时间</div>
                  <div class="status-value">{{ parseTime(sprint.startDate, '{y}-{m}-{d}') }}</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="status-item">
                  <div class="status-label">结束时间</div>
                  <div class="status-value">{{ parseTime(sprint.dueDate, '{y}-{m}-{d}') }}</div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-col>
      <el-col :span="16">
        <div class="grid-content chart-area">
          <div id="burnDownDiagram" :style="myChartStyle"></div>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="10">
      <el-col :span="12">
        <div class="grid-content">
          <div>迭代说明</div>
          <div v-html="sprint.description"></div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="grid-content chart-area">
          <div id="workItem" :style="myChartStyle"></div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import * as echarts from "echarts";
import {getSprint} from "@/api/projectUser/userSprint";
import {getWorkBySprintId} from "@/api/projectUser/userWork";
import UserAndAvatar from "@/components/UserAndAvatar/index.vue";

export default {
  name: "overviewInit",
  components: {UserAndAvatar},
  dicts: ['sprint_status', 'work_status', 'work_type'],
  data() {
    return {
      works: [],
      sprint: {},
      activeName: 'first',
      myChartStyle: {float: "left", width: "100%", height: "358px"} //图表样式
    }
  },
  props: {
    sprintId: {
      type: Number,
    },
    projectId: {
      type: Number,
    }
  },
  created() {
    this.getSprintData();
  },
  mounted() {
    // this.initEchartsBurnDownDiagram();
    // this.initEchartsWorkItem();
  },
  methods: {
    getSprintData() {
      getSprint(this.sprintId).then(response => {
        this.sprint = response.data;
        getWorkBySprintId(this.sprintId).then(res => {
          this.works = res.data;
          this.initEchartsBurnDownDiagram()
          this.initEchartsWorkItem()
        });
      });
    },
    /**
     * 计算燃尽图 并初始化
     */
    initEchartsBurnDownDiagram() {
      if (!this.sprint.startDate || !this.sprint.dueDate) return;
      let startDate = new Date(this.sprint.startDate);
      let endDate = new Date(this.sprint.dueDate);
      let dateArray = [];
      let currentDate = new Date(startDate);
      let dailyRemaining = [];
      let completedWork = {};

      while (currentDate <= endDate) {
        dateArray.push(currentDate.toISOString().split('T')[0]);
        currentDate.setDate(currentDate.getDate() + 1);
      }

      let remainingStoryPoints = this.works
        .filter(item => item.storyPoints !== null)
        .reduce((sum, item) => sum + item.storyPoints, 0);

      let idealLine = dateArray.map((date, index) =>
        remainingStoryPoints * (1 - index / (dateArray.length - 1))
      );

      this.works.forEach(item => {
        if ((item.status === "completed"||item.status === "close") && item.storyPoints !== null && item.completedAt) {
          let completedDate = new Date(item.completedAt).toISOString().split('T')[0];
          completedWork[completedDate] = (completedWork[completedDate] || 0) + item.storyPoints;
        }
      });

      dateArray.forEach(date => {
        if (completedWork[date]) {
          remainingStoryPoints -= completedWork[date];
        }
        dailyRemaining.push(remainingStoryPoints);
      });



      let option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['理想线', '剩余故事点数']
        },
        grid: {
          left: '3%',
          right: '3%',
          bottom: '2%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dateArray
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '理想线',
            type: 'line',
            data: idealLine,
          },
          {
            name: '剩余故事点数',
            type: 'line',
            data: dailyRemaining,
            areaStyle: {}
          },
        ]
      };
      echarts.init(document.getElementById('burnDownDiagram')).setOption(option);
    },
    /**
     * 计算工作项分布
     */
    initEchartsWorkItem() {
      // 获取所有工作类型并计算有效类型（排除全0类型）
      const allWorkTypes = Array.from(new Set(this.works.map(item => item.type)));
      const validWorkTypes = allWorkTypes.filter(type => {
        // 计算该类型在所有状态下的总数
        return this.works.some(work => work.type === type)
      });

      // 生成系列数据（自动过滤无效类型）
      const worksData = this.dict.type.work_status.map(status => {
        const data = validWorkTypes.map(type =>
          this.works.filter(work =>
            work.type === type && work.status === status.value
          ).length
        );

        return {
          name: status.label,
          type: 'bar',
          stack: 'total',
          label: {
            show: true,
            formatter: ({value}) => value > 0 ? value : '' // 隐藏0值标签
          },
          emphasis: {
            focus: 'series'
          },
          data
        };
      });

      // 生成图表配置
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {type: 'shadow'}
        },
        legend: {},
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        yAxis: {type: 'value'},
        xAxis: {
          type: 'category',
          data: validWorkTypes.map(type =>
            (this.dict.type.work_type.find(item => item.value === type) || {label: type}).label
          )
        },
        series: worksData
      };

      // 初始化图表
      echarts.init(document.getElementById('workItem')).setOption(option);
    }
  }
}
</script>


<style scoped lang="scss">

.el-row {
  margin-bottom: 10px;

  &:last-child {
    margin-bottom: 0;
  }
}

.grid-content {
  background: rgba(220, 227, 241, 0.74);
  border-radius: 8px;
  min-height: 400px;
  padding: 20px;
  box-sizing: border-box;

  .section-title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 25px;
  }

  .status-info {

    .status-item {
      height: 70px;
      margin-bottom: 10px;

      .status-label {
        font-size: 14px;
        color: #606266;
        margin-bottom: 5px;
      }

      .status-value {
        font-size: 14px;
        color: #303133;
      }
    }
  }

  .metrics-container {
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: 150px; // 减去标题、状态信息和padding高度
    margin-bottom: 20px;

    .metric-item {
      display: flex;
      flex-direction: column;
      align-items: center;

      .metric-label {
        font-size: 14px;
        color: #606266;
        margin-bottom: 15px;
      }

      .progress-circle {
        transition: transform 0.3s;

        &:hover {
          transform: scale(1.05);
        }
      }
    }
  }

  &.chart-area {
    background: rgba(255, 255, 255, 0.9);
    border: 1px solid #EBEEF5;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #909399;
    font-size: 16px;
  }
}
</style>
